package chzhenjia.learn.androidcode.two;

import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;
import android.support.v7.app.AppCompatActivity;
import android.text.format.Formatter;
import android.widget.TextView;

import chzhenjia.learn.androidcode.R;

/**
 * @author 陈圳佳
 *         日期:2015/7/14
 */
public class ShowTotalSdcardActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_total_sdcard);
        TextView totalSize = (TextView) findViewById(R.id.sdcard_tv_total_size);
        TextView available = (TextView) findViewById(R.id.sdcard_tv_available_size);
        totalSize.setText(getSdTotalSize());
        available.setText(getSdAvailableSize());
    }

    /**
     * 获得 sd 卡的总大小
     *
     * @return sd卡的大小
     */
    public String getSdTotalSize() {
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return "0";
        }
        StatFs statFs = new StatFs(Environment.getExternalStorageDirectory().getPath());
        long block;
        long count;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            //获得区块大小
            block = statFs.getBlockSizeLong();
            //获得sd卡所有区块的数量
            count = statFs.getBlockCountLong();
        } else {
            //获得区块大小
            block = statFs.getBlockSize();
            //获得sd卡所有区块的数量
            count = statFs.getBlockCount();
        }
        return Formatter.formatFileSize(this, count * block);
    }

    /**
     * 获取 sd 卡的剩余容量
     *
     * @return sd 的剩余容量
     */
    public String getSdAvailableSize() {
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return "0";
        }
        StatFs statFs = new StatFs(Environment.getExternalStorageDirectory().getPath());
        long block;
        long available;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            //获得区块大小
            block = statFs.getBlockSizeLong();
            //获取 sd卡的剩余区块数量
            available = statFs.getAvailableBlocksLong();
        } else {
            block = statFs.getBlockSize();
            //获取 sd卡的剩余区块数量
            available = statFs.getAvailableBlocks();
        }
        return Formatter.formatFileSize(this, available * block);
    }
}
